# name : rpact samplesize survival tempalte
# key : rpact.SampleSizeSurvival.template
# contributor: Shuguang Sun
# --
${1:sz_tte} <- function(x) {
  sz1 <- getSampleSizeSurvival(
    alpha = x$alpha, sided = 1,
    beta = x$beta,
    lambda1 = log(2) / x$active,
    lambda2 = log(2) / x$control,
    ## hazardRatio = x$hr,
    allocationRatioPlanned = x$ratio,
    followUpTime = 0,
    ## accrualTime: same length of accrualIntensity,
    accrualTime = seq_len(length(x$accrualIntensity)) - 1,
    accrualIntensity = x$accrualIntensity,
    dropoutRate1 = x$dropctr,
    dropoutRate2 = x$droptrt,
    dropoutTime = 12
  )

  sz2 <- getSampleSizeSurvival(
    alpha = x$alpha, sided = 1,
    beta = x$beta,
    lambda1 = log(2) / x$active,
    lambda2 = log(2) / x$control,
    ## hazardRatio = x$hr,
    allocationRatioPlanned = x$ratio,
    accrualTime = seq_len(length(x$accrualIntensity)) - 1,
    accrualIntensity = x$accrualIntensity,
    maxNumberOfSubjects = (x$ratio + 1) * floor(sz1$eventsFixed / x$eventratio / (x$ratio + 1)),
    dropoutRate1 = x$dropctr,
    dropoutRate2 = x$droptrt,
    dropoutTime = 12
  )

  ret <- c(
    alpha = x$alpha,
    power = 1 - x$beta,
    medianact = x$active,
    medianctr = x$control,
    hr = sz2$hazardRatio,
    nevent = ceiling(sz1$eventsFixed),
    N = ceiling(sz2$numberOfSubjects1) + ceiling(sz2$numberOfSubjects2),
    event_rate = ceiling(sz1$eventsFixed) /
      (ceiling(sz2$numberOfSubjects1) + ceiling(sz2$numberOfSubjects2)),
    mdd = sz2$criticalValuesEffectScale,
    ratio = x$ratio,
    accrualTime = max(sz2$accrualTime),
    studyDuration = sz2$studyDuration,
    followUpTime = sz2$followUpTime
  )
}

# median control time-to-event
medianC <- ${2:12}
# hypothesized experimental/control hazard ratio
# (alternate hypothesis)
hr <- ${3:0.6}
# Type I error (1-sided)
alpha <- ${4:0.025}
# Type II error (1-power)
beta <- ${5:0.1}
# enrollment rates fixed
accrualIntensity <- ${6:40}
# randomization ratio, experimental/control
ratio <- ${7:1}
# dropout rate in control group
dropctr <- 0.05
# dropout rate in treatment group
droptrt <- 0.05
# event ratio
eventratio <- ${8:0.75}


params <- expand.grid(alpha = alpha, beta = beta, ratio = ratio,
active = medianC / hr, control = medianC,
accrualIntensity = accrualIntensity,
dropctr = dropctr, droptrt = droptrt,
eventratio = eventratio)
paramsl <- lapply(seq_len(nrow(params)), function(i) params[i, ])
## paramsl <- lapply(seq_len(nrow(params)),
##                  \(i) c(as.list(params[i, ]), list(accrualIntensity = accrualIntensity)))

ns <- sapply(paramsl, $1)
